package drag.and.drop;

import get.data.DatabaseHandler;
import get.data.Main;
import get.data.R;
import get.data.myNode;
import java.util.ArrayList;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.os.Bundle;
import android.view.Display;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.AbsoluteLayout;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.FrameLayout.LayoutParams;

public class SetNodesPosition extends Activity 
	implements View.OnLongClickListener, View.OnClickListener{

	private DragController mDragController;   // Object that sends out drag-drop events while a view is being moved.
	private DragLayer mDragLayer;             // The ViewGroup that supports drag-drop.
	
	public static int screenwidth,screenheight;
	
	
	protected void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    mDragController = new DragController(this);
	    setContentView(R.layout.drag_n_drop_layout);
	    
	    LinearLayout ll = (LinearLayout) findViewById(R.id.layout1);
	    final int h = ll.getHeight();
	    
        WindowManager w = getWindowManager();
        Display d = w.getDefaultDisplay();
        int screenwidth = d.getWidth();
        int screenheight = d.getHeight(); 
	    
        Button cancel = (Button) findViewById(R.id.cancel);
        cancel.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
					finish();
			}});
	    
        final Button save = (Button) findViewById(R.id.save);
        save.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				
				getCoordinates(); 
				Main.db.close();
	    		String myPath = DatabaseHandler.DB_PATH+ DatabaseHandler.DB_NAME;
	    		Main.db = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);

			        //insert rows
				try{
					String sql = "DROP table "+DatabaseHandler.NODES;
					Main.db.execSQL(sql);
				}catch(Exception e){}
				DatabaseHandler.createNodesTable(Main.db);
			    for(int i=0;i<Main.nodes.size();i++){
			       	myNode currentnode = Main.nodes.get(i);
			       	int x = currentnode.GetX();
			       	int y = currentnode.GetY()-98;
			       	String sql ="INSERT INTO " + DatabaseHandler.NODES+" (id,ip,coordx,coordy) VALUES ('"+currentnode.GetId() + "','"+currentnode.GetAdd()+"',"+  x+","+  y+")";
			       	System.out.println(sql);
			       	Main.db.execSQL(sql);
			    }					
			
		        Main.db.close();
		        finish();
			}
		});
        save.setKeepScreenOn(true);
        setupViews() ;
   	}
	
	public void onClick(View v) {
	    Toast.makeText (getApplicationContext(), 
                "Long click to move the node.", Toast.LENGTH_LONG).show ();	    
	}
	
    public void getCoordinates(){
    	
        for (int i = 0; i < Main.nodes.size(); i++) {
            View child = Main.nodes.get(i).GetDraw();
	    	int[] location = new int[10];
	        child.getLocationOnScreen(location);
	        System.out.println(location[0]+" "+location[1]);
	        Main.nodes.get(i).SetPosition(location[0], location[1]);
        }
    }

	public boolean onLongClick(View v) {    
	    
	    return startDrag (v);

	}
	
	public boolean startDrag (View v)
	{
	    Object dragInfo = v;
	    mDragController.startDrag (v, mDragLayer, dragInfo, DragController.DRAG_ACTION_MOVE);
	    return true;
	}
	
	/**
	 * Finds all the views we need and configure them to send click events to the activity.
	 *
	 */
	private void setupViews() 
	{
		DragController dragController = mDragController;
	
	    mDragLayer = (DragLayer) findViewById(R.id.drag_layer);
	    mDragLayer.setDragController(dragController);
	    dragController.addDropTarget (mDragLayer);
	    
	    //get nodes from database or from memory
		String myPath = DatabaseHandler.DB_PATH+ DatabaseHandler.DB_NAME;
		Main.db = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
		//ArrayList<DrawView> objects = new ArrayList<DrawView>();
		ArrayList<ImageView> objects = new ArrayList<ImageView>();
		for(int i=0;i<Main.nodes.size();i++){			
			int coordx = 0;
			int coordy = 0;
		    /*if(DatabaseHandler.checkDataBase(Main.db)) {
				//put object at specific coordinates
				//get coordinates
				String sql = "SELECT * FROM "+ DatabaseHandler.NODES + " WHERE id='"+Main.nodes.get(i).GetId()+"'";
				Cursor c = Main.db.rawQuery(sql, null);
				System.out.println(c.getCount());
				c.moveToFirst();
				if (c != null) {
					coordx = c.getInt(3);
					coordy = c.getInt(4);
					System.out.println(coordx+" "+coordy+"");
				}
				c.close();
		    }*/
		 
			DrawView dw;
			dw = new DrawView(this,Main.nodes.get(i).GetId(),coordx,coordy);
			Bitmap bt;
	        bt = Bitmap.createBitmap(50, 50, Bitmap.Config.ARGB_8888);
			Canvas c = new Canvas(bt);
			dw.layout(50, 50, 100, 100);
	        dw.draw(c);
	        ImageView iv = new ImageView(this);
	        iv.setImageBitmap(bt);
	        iv.layout(50, 50, 100, 100);
			
			//dw.layout(50, 50, 90, 100);
			//dw.setLayoutParams(new LayoutParams(50, 50));
			iv.setId(i);
			iv.setOnClickListener(this);
			iv.setOnLongClickListener(this);
			objects.add(iv);
			Main.nodes.get(i).SetDraw(iv);
				
	    }

		for(int k=0;k<objects.size();k++){
			mDragLayer.addView(Main.nodes.get(k).GetDraw());
			//mDragLayer.addView(objects.get(k));
		}

	    Toast.makeText (getApplicationContext(), 
	                    "Drag and drop the nodes according to their physical position.", Toast.LENGTH_LONG).show ();
	
	}
    public void onStop ()
    {
    	super.onStop();
    	Main.db.close();
    }

} 
